import copy


class NumMatrix(object):

    def __init__(self, matrix):
        """
        :type matrix: List[List[int]]
        """
        self.matrix = matrix
        self.m = len(self.matrix)
        self.n = len(self.matrix[0])
        self.h_matrix = [[0] * self.n for _ in range(self.m)]
        for i in range(self.m):
            for j in range(self.n):
                if j == 0:
                    self.h_matrix[i][j] = self.matrix[i][j]
                else:
                    self.h_matrix[i][j] = self.matrix[i][j] + self.h_matrix[i][j - 1]

    def update(self, row, col, val):
        """
        :type row: int
        :type col: int
        :type val: int
        :rtype: None
        """
        diff = val - self.matrix[row][col]
        self.matrix[row][col] = val
        for j in range(col, self.n):
            self.h_matrix[row][j] += diff

    def sumRegion(self, row1, col1, row2, col2):
        """
        :type row1: int
        :type col1: int
        :type row2: int
        :type col2: int
        :rtype: int
        """
        num = 0
        for i in range(row1, row2 + 1):
            if col1 > 0:
                num += (self.h_matrix[i][col2] - self.h_matrix[i][col1 - 1])
            else:
                num += self.h_matrix[i][col2]
        return num


matrix = [[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]
cod = NumMatrix(matrix)
print(cod.h_matrix)
cod.update(3, 2, 2)
print(cod.h_matrix)
print(cod.sumRegion(2, 1, 4, 3))
